

import 'dart:convert';
import 'dart:typed_data';

import 'package:dio/dio.dart';
import 'package:fast_rsa/fast_rsa.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:pointycastle/ecc/api.dart';
import 'package:xim/common/util/ecc.dart';
import 'package:xim/common/util/secp256.dart';
import 'package:xim/config/route_config.dart';
import 'package:xim/config/store_config.dart';
import 'package:xim/http/apis.dart';
import 'package:xim/http/apis/user/user_model.dart';
import 'package:xim/http/http.dart';
import 'package:xim/http/rsa.dart';
import 'package:xim/http/store.dart';

/// 用户模块
class UserApi {

  /// 用户搜索(用户名称、账号)
  static Future<List<UserInfoModel>> searchByUname(String name) async {
    var respData = await dio.postResult("/user/search", queryParameters: {"account": name});
    var listDates = respData.data as List;
    return listDates.map((e) => UserInfoModel.fromJson(e)).toList();
  }

  /// 用户搜索(用户名称、账号)
  static Future<List<UserInfoModel>> searchByAccount(String account) async {
    var respData = await dio.postResult("/user/search", queryParameters: {"account": account});
    var listDates = respData.data as List;
    return listDates.map((e) => UserInfoModel.fromJson(e)).toList();
  }

  /// 获取用户信息
  static Future<UserInfoModel> queryUserInfo({String? account}) async{
    Options options = Options().addHeader('cached', true);
    var resp = await dio.get(
        "/user/query/info",
        queryParameters: {"account": account},
        options: options
    );
    return UserInfoModel.fromJson(resp.data['data']);
  }

  /// 批量获取用户信息
  static Future<List<UserInfoModel>> queryUserInfoBatch(Set<String> accounts) async {
    var resp = await dio.postResult("/user/query/info/batch", data: json.encode(accounts.toList()));
    var lst = resp.data as List<dynamic>;
    return lst.map((e) => UserInfoModel.fromJson(e)).toList();
  }

  /// 获取所有好友列表
  /// [status] 1:正常状态, 2:待同意,
  static Future<List<UserFriendModel>> queryFriends({int? status=1}) async {
    var result = await dio.postResult("/user/friend/query/list",
        queryParameters: {"status":status}, cached: false);
    var data = result.data as List<dynamic>;
    return data.map((e) => UserFriendModel.fromJson(e)).toList();
  }

  /// 添加好友
  static Future<void> requestAddFriend(String account) async {
    var result = await dio.postResult("/user/friend/add", queryParameters: {"account": account});
    return Future(() => null);
  }

  /// 获取用户的公钥地址 TODO add api
  static Future<String?> queryUserPublicKey(String account) async {
    var resp =  await queryUserInfo(account: account);
    return resp.publicKey;
  }

  /// 获取登录令牌
  static Future<String> requestUserLoginToken({required String hexPublicKey}) async {
    var res = await dio.post(
        "/user/login/token",
        queryParameters: {"publicKey": hexPublicKey}
    );
    String data = res.data['data'];
    return data;
  }

  static userLogin() async {
    var hasBindUser = await StoreApi.instance.hasBindUser();
    if (hasBindUser){
      Routers.toLoginGuidePage();
      return;
    }
    var publicKey = await StoreApi.instance.secureTakeUserPublicKey();
    var privateKey = await StoreApi.instance.secureTakeUserPrivateKey();
    var token = await UserApi.requestUserLoginToken(hexPublicKey: publicKey!);
    var plainTextRegisterToken = EccUtil.decryptHex(token, privateKey!);
    var signToken = EccUtil.sign(plainTextRegisterToken, privateKey);
    await UserApi.login(hexPubKey: publicKey, signToken: signToken);
  }

  /// 用户登录
  static login({required String hexPubKey, required String signToken}) async {
    var resp = await dio.post("/user/login", queryParameters: {
      "hexPublicKey": hexPubKey,
      "signToken": signToken,
    });
    var token = resp.data['data'];
    await StoreApi.instance.storeUserToken(token);
  }

  /// 删除好友
  static Future<ResponseResult> deleteFriend(String friendAccount) async {
    return dio.ajaxPost("/user/friend/delete", queryParameters: {"friendAccount": friendAccount});
  }

}